package com.qi.spzx.manager.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qi.spzx.common.exception.GuiguException;
import com.qi.spzx.manager.mapper.CategoryBrandMapper;
import com.qi.spzx.manager.service.BrandService;
import com.qi.spzx.manager.service.CategoryBrandService;
import com.qi.spzx.model.dto.product.CategoryBrandDto;
import com.qi.spzx.model.entity.product.Brand;
import com.qi.spzx.model.entity.product.CategoryBrand;
import com.qi.spzx.model.vo.common.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author dingchunlin
 * @Date 2024/2/23 16:57
 * @Version 1.0.0
 */
@Service
public class CategoryBrandServiceImpl implements CategoryBrandService {

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Autowired
    private BrandService brandService;

    @Override
    public PageInfo<CategoryBrand> findByPage(Integer page, Integer limit, CategoryBrandDto categoryBrandDto) {
        PageHelper.startPage(page,limit);
        List<CategoryBrand> list = categoryBrandMapper.findByPage(categoryBrandDto);
        return PageInfo.of(list);
    }

    @Override
    public void save(CategoryBrand categoryBrand) {
        //在进行添加之前判断是否已经添加过了
        Integer count = categoryBrandMapper.isAdd(categoryBrand);
        if (count > 0) {
            throw new GuiguException(ResultCodeEnum.BRAND_CATELOG_IS_EXISTS);
        }
        //进行添加
        categoryBrandMapper.save(categoryBrand);
    }

    @Override
    public void updateById(CategoryBrand categoryBrand) {
        //在修改之前要判断修改后的是否存在
        Integer count = categoryBrandMapper.isAdd(categoryBrand);
        if (count > 0) {
            throw new GuiguException(ResultCodeEnum.BRAND_CATELOG_IS_EXISTS);
        }
        categoryBrandMapper.updateById(categoryBrand);
    }

    @Override
    public void deleteById(Long id) {
        categoryBrandMapper.deleteById(id);
    }

    @Override
    public List<Brand> findBrandByCategoryId(Long categoryId) {
        List<Brand> brandList = new ArrayList<>();
        List<Long> brandIds =  categoryBrandMapper.findBrandByCategoryId(categoryId);
        for (Long brandId : brandIds) {
            Brand brand = brandService.selectById(brandId);
            if (ObjectUtil.isNotEmpty(brand)) {
                brandList.add(brand);
            }
        }
        return brandList;
    }
}
